//
//  TuyaManager.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/4/24.
//

import Foundation
import Combine
import ThingSmartHomeKit
import ThingSmartDeviceKit
import ThingSmartFamilyBizKit
import ThingSmartActivatorDiscoveryManager

fileprivate let defaultError = NSError(domain: "涂鸦ERROR", code: -1, userInfo: [NSLocalizedDescriptionKey: "无错误描述"])

class TuyaManager {
    static let shared = TuyaManager()
    var homeId: Int64?
    
    private let tuyaHomeManager = ThingSmartHomeManager()
     var currentHome: ThingSmartHome!
    private var currentHomeModel: ThingSmartHomeModel!
    private var homeList: [ThingSmartHomeModel]?
    private var productPrimaryCategory: ThingSmartACategoryModel?
    
    //Thread 1: "you must add thing_custom_config.json in mainBundle."
    private init() {
        // 初始化中获取一些必要信息
    }
    
    func getCurrentHome() -> ThingSmartHome! {
        return currentHome
    }
    
    // 涂鸦账号密码登陆
    func login(_ phone: String, password: String) -> AnyPublisher<Void, Error>
    {
        return TuyaLoginPwdStep().execute(.init(account: phone, password: password))
    }
    
    
    func go(deviceModel:ThingSmartDeviceModel)
    {
//        let impl = ThingSmartBizCore.sharedInstance().service(of: ThingPanelProtocol.self) as? ThingPanelProtocol
//        // 获取面板视图控制器，自动跳转
//        impl?.gotoPanelViewController(withDevice: deviceModel, group: nil, initialProps: nil, contextProps: nil, completion: { (error: Error?) in
//            print(error.debugDescription)
//        })
    }
    
    func isLogin() -> Bool {
        return ThingSmartUser.sharedInstance().isLogin
    }
    
    func requestHomeList() -> AnyPublisher<[ThingSmartHomeModel], Error>{
        if isLogin() == false {
            return Fail(error: NSError(domain: "涂鸦ERROR", code: -1, userInfo: [NSLocalizedDescriptionKey: "用户未登录"])).eraseToAnyPublisher()
        }
        return internalGetHomeList()
            .retry(3)
            .flatMap { homeList -> AnyPublisher<Void, Error> in
                guard !homeList.isEmpty else {
                    return self.internalCreateHome()
                }
                self.homeId = homeList.first?.homeId
                if let homeId = self.homeId
                {
                    self.currentHome = ThingSmartHome.init(homeId: homeId)
                    self.currentHomeModel = self.currentHome.homeModel
                    return self.getHomeDetail()
                }
                self.homeList = homeList
                return Just(()).setFailureType(to: Error.self).eraseToAnyPublisher()
            }
            .retry(3)
            .flatMap { _ in
                self.internalGetHomeList()
            }
            .retry(3)
            .eraseToAnyPublisher()
    }
    
    // 获取产品分类
     func requestPrimaryCategory() -> AnyPublisher<ThingSmartACategoryModel, Error> {
            Future { promise in
                let requestService = ThingSmartActivatorDiscoveryRequest()
                let requestData = ThingActivatorPrimaryCategoryRequestData()
                
                requestService.requestPrimaryCategory(withParam: requestData) { result in
                    let nsData = result.yy_modelToJSONData()
                    if let nsData = nsData,
                       let string = String(data: nsData, encoding: .utf8) {
                        print("转换成功：\(string)")
                    } else {
                        print("nsData 为 nil 或转换失败")
                    }
                    promise(.success(result))
                } failure: { error in
                    promise(.failure(error))
                }
            }
            .eraseToAnyPublisher()
        }
    
    func requestSecondaryCategory(level1code: String, type: String) -> AnyPublisher<[ThingSmartACategoryLevel2Model], Error>
    {
        Future { promise in
            let requestService = ThingSmartActivatorDiscoveryRequest()
            let requestData =  ThingActivatorSecondaryCategoryRequestData()
            requestData.levelOneCode = level1code
            requestData.type = type
            requestService.requestSecondaryCategory(withParam: requestData) { result in
                let nsData = result.first!.yy_modelToJSONData()
                if let nsData = nsData,
                   let string = String(data: nsData, encoding: .utf8) {
                    print("转换成功：\(string)")
                } else {
                    print("nsData 为 nil 或转换失败")
                }
                promise(.success(result))
            } failure: { error in
                promise(.failure(error))
            }
        }
        .eraseToAnyPublisher()
    }
    
    // 获取当前home数据
    private func getHomeDetail() -> AnyPublisher<Void, Error>
    {
        Future { promise in
            self.currentHome.getDataWithSuccess({ model in
                if let model = model {
                    promise(.success(()))
                }
                else {
                    promise(.failure(defaultError))
                }
            }, failure: { error in
                promise(.failure(error ?? defaultError))
            })
        }
        .eraseToAnyPublisher()
    }
    
    private func internalGetHomeList() -> AnyPublisher<[ThingSmartHomeModel], Error>
    {
        Future { promise in
            self.tuyaHomeManager.getHomeList(success: { modelList in
                promise(.success(modelList ?? []))
            }, failure: { error in
                promise(.failure(error ?? defaultError))
            })
        } .catch { _ in
            Just([]) // 如果失败，返回空数组
                .setFailureType(to: Error.self)
                .eraseToAnyPublisher()
        }.eraseToAnyPublisher()
    }
    
    private func internalCreateHome() -> AnyPublisher<Void, Error>
    {
        Future { promise in
            self.tuyaHomeManager.addHome(withName: "My Home", geoName: "", rooms: [], latitude: 0, longitude: 0, success: {result in
                promise(.success(()))
            }, failure: { error in
                promise(.failure(error ?? defaultError))
            })
        } .catch { _ in
            Just(()) // 如果失败，返回空数组
                .setFailureType(to: Error.self)
                .eraseToAnyPublisher()
        }.eraseToAnyPublisher()
    }
    
    

    
}
